import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/screen_util.dart';
import 'package:study_online/entity/Course.dart';
import 'package:study_online/global/myIcons.dart';
import 'package:study_online/pages/studyPage/views/CourseIntroduceTab.dart';

import 'package:flutter/material.dart';

import '../StudyModel.dart';
import 'CourseCatalogueTab.dart';
import 'CourseRemarkTab.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      builder: EasyLoading.init(),
      home: Scaffold(
        //appBar: AppBar(
        //  backgroundColor: Colors.black26,
        //  title: Text('container'),
        //),
        body: CourseDetailPage('1','',1,1),
      ),
    );
  }
}

class CourseDetailPage extends StatefulWidget {
  String title,photo;
  int pri;
  int couId;
  CourseDetailPage(this.title,this.photo,this.pri,this.couId);
  @override
  _CourseDetailPageState createState() => _CourseDetailPageState();
}

class _CourseDetailPageState extends State<CourseDetailPage>
    with SingleTickerProviderStateMixin {
  CourseDetail _course;
  TabController tabController;
  List<Tab> _tabs;
  List<Widget> _tabViews;
  void _loadData() async {
    Response response=await getCourseInfoById(widget.couId);
    print("###"+response.toString());
    var responseData=json.decode(response.toString());
    setState(() {
      _course=CourseDetail.fromJson(responseData);
      print("###"+_course.toString());
    });
  }
  @override
  void initState() {
    super.initState();
    _loadData();
    _tabs = [
      Tab(text: "介绍"),
      Tab(text: "目录"),
      Tab(text: "评价"),
    ];
    _tabViews = [
      Container(
        color: Colors.white,
        child: CourseIntroduceTab(),
      ),
      Container(
        color: Colors.white,
        child: CourseCatalogueTab(),
      ),
      Container(
        color: Colors.white,
        child: CourseRemarkTab(couId: widget.couId),
      ),
    ];
    this.tabController = TabController(length: _tabs.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    //debugPaintSizeEnabled=true;
    var passValue = ModalRoute.of(context).settings.arguments;
    ScreenUtil.init(
      BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width,
          maxHeight: MediaQuery.of(context).size.height),
      designSize: Size(1080, 2340),
    );

      return Container(
        color: Colors.black,
        child: Stack(
          children: [
            Container(
              margin: EdgeInsets.only(
                  bottom:
                  ScreenUtil().screenHeight - ScreenUtil().setHeight(2140)),
              child: CustomScrollView(
                slivers: <Widget>[
                  SliverPersistentHeader(
                    pinned: true,
                    delegate: SliverCustomHeaderDelegate(
                      title: '${widget.title}',
                      collapsedHeight: ScreenUtil().setHeight(122),
                      expandedHeight: ScreenUtil().setHeight(630),
                      paddingTop: MediaQuery.of(context).padding.top,
                      coverImgUrl: widget.photo,
                      tag: passValue.toString(),
                    ),
                  ),
                  SliverPersistentHeader(
                    pinned: true,
                    delegate: StickyTabBarDelegate(
                      child: TabBar(
                        labelColor: Colors.black,
                        controller: this.tabController,
                        tabs: _tabs,
                      ),
                    ),
                  ),
                  SliverFillRemaining(
                    child: TabBarView(
                      controller: this.tabController,
                      children: _tabViews,
                    ),
                  ),
                ],
              ),
            ),
            Positioned(
              left: 0,
              top: ScreenUtil().setHeight(2140),
              child: Container(
                height: ScreenUtil().screenHeight - ScreenUtil().setHeight(2140),
                width: ScreenUtil().screenWidth,
                decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(
                    top: BorderSide(
                        color: Colors.black12, width: ScreenUtil().setWidth(2)),
                  ),
                ),
                padding: EdgeInsets.fromLTRB(ScreenUtil().setWidth(76),
                    ScreenUtil().setHeight(44), ScreenUtil().setWidth(76), 0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: ScreenUtil().setWidth(80),
                      height: ScreenUtil().setHeight(135),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Icon(
                            MyIcons.customerService,
                            size: ScreenUtil().setSp(56),
                          ),
                          Text(
                            '客服',
                            style: TextStyle(
                              fontSize: ScreenUtil().setSp(40),
                              color: Colors.black,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: ScreenUtil().setWidth(80),
                      height: ScreenUtil().setHeight(135),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Icon(
                            Icons.star_outline_rounded,
                            size: ScreenUtil().setSp(76),
                          ),
                          Text(
                            '收藏',
                            style: TextStyle(
                              fontSize: ScreenUtil().setSp(40),
                              color: Colors.black,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: ScreenUtil().setWidth(695),
                      height: ScreenUtil().setHeight(129),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(
                            Radius.circular(ScreenUtil().setHeight(129) * 0.5)),
                        gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.center,
                          stops: [0.0, 1.0],
                          colors: [Color(0xD58FC9B5), Color(0xff5fdbb3)],
                        ),
                      ),
                      child: Center(
                        child: Text(
                          widget.pri==0?'立即学习':'仅${widget.pri}元 立即购买',
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(52),
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      );
  }
}

class SliverCustomHeaderDelegate extends SliverPersistentHeaderDelegate {
  final double collapsedHeight;
  final double expandedHeight;
  final double paddingTop;
  final String coverImgUrl;
  final String title;
  final String tag;
  String statusBarMode = 'dark';

  SliverCustomHeaderDelegate({
    this.collapsedHeight,
    this.expandedHeight,
    this.paddingTop,
    this.coverImgUrl,
    this.title,
    this.tag
  });

  @override
  double get minExtent => this.collapsedHeight + this.paddingTop;

  @override
  double get maxExtent => this.expandedHeight;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }

  void updateStatusBarBrightness(shrinkOffset) {
    if (shrinkOffset > 50 && this.statusBarMode == 'dark') {
      this.statusBarMode = 'light';
      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        statusBarBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.light,
      ));
    } else if (shrinkOffset <= 50 && this.statusBarMode == 'light') {
      this.statusBarMode = 'dark';
      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        statusBarBrightness: Brightness.dark,
        statusBarIconBrightness: Brightness.dark,
      ));
    }
  }

  Color makeStickyHeaderBgColor(shrinkOffset) {
    final int alpha = (shrinkOffset / (this.maxExtent - this.minExtent) * 255)
        .clamp(0, 255)
        .toInt();
    return Color.fromARGB(alpha, 255, 255, 255);
  }

  Color makeStickyHeaderTextColor(shrinkOffset, isIcon) {
    if (shrinkOffset <= 50) {
      return isIcon ? Colors.white : Colors.transparent;
    } else {
      final int alpha = (shrinkOffset / (this.maxExtent - this.minExtent) * 255)
          .clamp(0, 255)
          .toInt();
      return Color.fromARGB(alpha, 0, 0, 0);
    }
  }

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    this.updateStatusBarBrightness(shrinkOffset);
    return Container(
      height: this.maxExtent,
      width: MediaQuery.of(context).size.width,
      child: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          Hero(
            tag: "HeroAnimationTag"+tag,
            child: Container(
              child: Image.network(
                coverImgUrl,
                fit: BoxFit.cover,
              ),
              //child: Image.network(this.coverImgUrl, fit: BoxFit.cover),
            ),
          ),
          Positioned(
            left: 0,
            top: this.maxExtent / 2,
            right: 0,
            bottom: 0,
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Color(0x00000000),
                    Color(0x90000000),
                  ],
                ),
              ),
            ),
          ),
          Positioned(
            left: 0,
            right: 0,
            top: 0,
            child: Container(
              color: this.makeStickyHeaderBgColor(shrinkOffset),
              child: SafeArea(
                bottom: false,
                child: Container(
                  height: this.collapsedHeight,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      IconButton(
                        icon: Icon(
                          Icons.arrow_back,
                          color: this
                              .makeStickyHeaderTextColor(shrinkOffset, true),
                        ),
                        onPressed: () => Navigator.pop(context),
                      ),
                      Text(
                        this.title,
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.w500,
                          color: this
                              .makeStickyHeaderTextColor(shrinkOffset, false),
                        ),
                      ),
                      IconButton(
                        icon: Icon(
                          MyIcons.share,
                          color: this
                              .makeStickyHeaderTextColor(shrinkOffset, true),
                          size: ScreenUtil().setSp(40),
                        ),
                        onPressed: () {},
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar child;

  StickyTabBarDelegate({@required this.child});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
            topRight: Radius.circular(16), topLeft: Radius.circular(16)),
        color: Colors.white,
      ),
      child: this.child,
    );
    ;
  }

  @override
  double get maxExtent => this.child.preferredSize.height;

  @override
  double get minExtent => this.child.preferredSize.height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}
